package cn.wsalix.weixin.service.impl;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.wsalix.admin.entity.SysUser;
import cn.wsalix.config.AppConfig;
import cn.wsalix.constant.WxGlobal;
import cn.wsalix.login.form.WxCodeForm;
import cn.wsalix.observable.service.LoginService;
import cn.wsalix.shiro.token.WxAppToken;
import cn.anlaser.utils.FastJsonMapper;
import cn.anlaser.utils.HttpUtils;
import cn.wsalix.weixin.entity.WxConfig;
import cn.wsalix.weixin.entity.WxMessage;
import cn.wsalix.weixin.req.entity.ImageReqMsg;
import cn.wsalix.weixin.req.entity.LinkReqMsg;
import cn.wsalix.weixin.req.entity.LocationReqMsg;
import cn.wsalix.weixin.req.entity.QrCodeEvent;
import cn.wsalix.weixin.req.entity.TextReqMsg;
import cn.wsalix.weixin.req.entity.VoiceReqMsg;
import cn.wsalix.weixin.req.service.TextReqMsgService;
import cn.wsalix.weixin.service.WxConfigService;
import cn.wsalix.weixin.service.WxMessageService;
import cn.wsalix.weixin.service.WxService;
import cn.wsalix.weixin.service.WxUserService;

@Service("wxService")
@Transactional(readOnly = true)
public class WxServiceImpl implements WxService {
	private static final Logger logger = LoggerFactory
			.getLogger(WxService.class);
	@Autowired
	private AppConfig appConfig;
	@Autowired
	private WxConfigService wxConfigService;
	@Autowired
	private TextReqMsgService textReqMsgService;
	@Autowired
	private WxUserService wxUserService;

	@Transactional()
	@Override
	public void saveTextReqMsg(TextReqMsg textReqMsgSrc) {
		textReqMsgService.add(textReqMsgSrc);
	}

	@Transactional()
	@Override
	public void saveImageReqMsg(ImageReqMsg imageReqMsg) {
		// TODO Auto-generated method stub

	}

	@Transactional()
	@Override
	public void saveVoiceReqMsg(VoiceReqMsg voiceReqMsg) {
		// TODO Auto-generated method stub

	}

	@Transactional()
	@Override
	public void saveQrCodeEvent(QrCodeEvent qrCodeEvent) {
		// TODO Auto-generated method stub

	}

	@Transactional()
	@Override
	public void saveLocationReqMsg(LocationReqMsg qrCodeEvent) {
		// TODO Auto-generated method stub

	}

	@Transactional()
	@Override
	public void saveLinkReqMsg(LinkReqMsg qrCodeEvent) {
		// TODO Auto-generated method stub

	}

	@Autowired
	private WxMessageService wxMessageService;

	@Transactional()
	@Override
	public WxMessage saveWxMessage(WxMessage wxMessage) {
		return wxMessageService.add(wxMessage);
	}
	@Transactional
	@Override
	public String oauth2(WxConfig wxConfig, String backUrl) {		
		// String redirectUri =
		// String.format(appConfig.getWxRedirectUri(),wxConfigId);
		String redirectUri = String.format(WxGlobal.AUTH_REDIRECT_URI,
				appConfig.getDomainName(), appConfig.getAppPath(), wxConfig.getId(),
				backUrl);
		try {
			String serverUrl = URLEncoder.encode(redirectUri, "utf-8");
			// 检查是否已验证或者验证是否通过
			String scope = "snsapi_userinfo";// snsapi_base/snsapi_userinfo
			String state = "STATE";
			String wxCodeUrl = WxGlobal.doGetWxCode(wxConfig.getAppId(),// "wxf7817ca93cf3c1e2",//WxGlobal.APPID,
					serverUrl, scope, state);
			logger.info("wxCodeUrl:" + wxCodeUrl);
			return wxCodeUrl;
			// String wxCodeLine = HttpUtils.getToString(wxCodeUrl);
			// logger.info("wxCodeLine:" + wxCodeLine);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}

	@Autowired
	private LoginService loginService;
	@Transactional
	@Override
	public SysUser register(WxConfig wxConfig, WxCodeForm form) {
		//WxConfig wxConfig = wxConfigService.findByConfigId(wxConfigId);//须查看文档，通过code获取Access_token是否app特例？
		String wxCodeUrl = WxGlobal.doGetAccessTokenByCode(form.getCode(),
				wxConfig.getAppId(), wxConfig.getAppSecret());
		logger.info("getAccessTokenByCode:" + wxCodeUrl);
		String wxCodeLine = HttpUtils.getToString(wxCodeUrl);
		logger.info("wxCodeLine:" + wxCodeLine);
		/*
		 * WxAccessToken wx//未传入Access_token，信息不可信 = FastJsonMapper.fromJson(wxCodeLine,
		 * WxAccessToken.class);
		 */
		WxAppToken wxAppToken = FastJsonMapper.fromJson(wxCodeLine,
				WxAppToken.class);
		wxAppToken.setMainRole(form.getMainRole());
		// 以下可直接调用 @WxUserService.add
		SysUser user = loginService.login(wxAppToken);
		//user.setWxUser(wxAppToken.getWxUser());
		logger.info("::"+FastJsonMapper.toJson(wxAppToken.getWxUser()));
		/*
		 * String wxUserInfoUrl = WxGlobal.doGetAppUserInfo(
		 * wxAccessToken.getAccess_token(), wxAccessToken.getOpenid());
		 * logger.info("wxUserInfoUrl:" + wxUserInfoUrl); String userInfoLine =
		 * HttpUtils.getToString(wxUserInfoUrl); logger.info("userInfoLine:" +
		 * userInfoLine); WxUser wxUser = FastJsonMapper.fromJson(userInfoLine,
		 * WxUser.class); wxUserService.add(wxUser);
		 */
		return user;
	}

}
